<template>
  <div class="alarmManagement">
    <div class="alarmManagement_treeBg">
      <MetaChoiceList
        ref="alarmManagement_list"
        title="报警等级"
        title-btn=""
        :list-data="alarmLevelDataStr"
        @roloeItemChoose="roloeItemChoose"
        :treeBtn="choiceListTreeBtn"
      />
    </div>
    <div class="alarmManagement_infoBg">
      <div class="alarmManagement_info">
        <div
          v-if="Object.keys(roleInfoItem).length > 0"
          class="alarmManagementO_rightArea"
        >
          <MetaSearchForm @on-search="tableSearch">
            <el-form
              ref="alarmManagement_searchForm"
              :model="searchData"
              label-width="80px"
            >
              <el-form-item label="设备名称" class="alarmManagement_searchFromItem">
                <el-input
                  v-model="searchData.equipmentName"
                  placeholder="请输入设备名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="报警时间" class="alarmManagement_searchFromItem">
                <el-date-picker
                  v-model="searchData.dateBetween"
                  type="daterange"
                  range-separator="-"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
              <el-row style="float: left">
                <el-col :span="8">
                  <el-form-item label="省" class="alarmManagement_searchFromItem">
                    <el-select
                      v-model="searchData.province"
                      placeholder="请选择省"
                      @change="provinceHandleChange"
                      clearable
                    >
                      <el-option
                        v-for="item in provinceList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="市" class="alarmManagement_searchFromItem">
                    <el-select
                      v-model="searchData.city"
                      placeholder="请选择市"
                      @change="cityHandleChange"
                      clearable
                    >
                      <el-option
                        v-for="item in cityList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="区" class="alarmManagement_searchFromItem">
                    <el-select
                      v-model="searchData.areaid"
                      placeholder="请选择区"
                      clearable
                    >
                      <el-option
                        v-for="item in areaList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </MetaSearchForm>
          <div class="alarmManagementTable_bg">
            <el-collapse v-model="collapseActiveNames">
              <el-collapse-item
                :title="item.typeValue + '（' + item.dataList.length + '台）'"
                :name="item.typeKey"
                v-for="(item, index) in currentAlarmTableData"
                :key="item.typeKey"
              >
                <MetaPageTable
                  :ref="'alarmManagementTable_' + index"
                  class="alarmManagementTable"
                  table-title="报警设备列表"
                  :need-checkbox="false"
                  tableHeight=""
                  :is-auto-req="false"
                  :tableData="item.tableData"
                  :display-item="displayItem"
                  :line-btn-group="lineBtnGroup"
                  @lineBtnClick="tableInlineBtnClick"
                  :remarkKey="item.typeKey"
                />
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-if="alarmRecordDialogFlag"
      title="报警记录"
      :visible.sync="alarmRecordDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="alarmRecord_form" :model="alarmRecordItem" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备名称" class="alarmRecordForm_item">
              {{ alarmRecordItem.equipmentName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备所在地" class="alarmRecordForm_item">
              {{ alarmRecordItem.equipmentName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="初次报警时间" class="alarmRecordForm_item">
              {{ alarmRecordItem.warningTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="报警等级" class="alarmRecordForm_item">
              {{ alarmRecordItem.warningLevel }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报警类型" class="alarmRecordForm_item">
              {{ alarmRecordItem.warningType }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="维修状态" class="alarmRecordForm_item">
              {{ alarmRecordItem.warningStatusName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修人" class="alarmRecordForm_item">
              {{ alarmRecordItem.username }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <MetaPageTable
        ref="alarmRecordTable"
        class="alarmRecordTable"
        table-title="报警记录"
        tableHeight="300"
        :need-checkbox="false"
        :is-auto-req="false"
        :tableData="alarmRecordData"
        :display-item="alarmRecordDisplayItem"
      />
      <div class="dialogFooter">
        <el-button size="mini" @click="closeAlarmRecordDialog()">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="repairToDialogFlag"
      title="维修指派"
      :visible.sync="repairToDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="repair_form"
        :model="repairInfoItem"
        label-width="110px"
        :rules="repairRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="报警类型" class="repairTo_formItem">{{
              repairInfoOnChoose.warningType
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警等级" class="repairTo_formItem">{{
              repairInfoOnChoose.warningLevel
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报警说明" class="repairTo_formItem">{{
          repairInfoOnChoose.warningContent
        }}</el-form-item>
        <el-form-item
          label="维修人"
          prop="userId"
          class="repairTo_formItem repairTo_user"
        >
          <div class="repairToOtherItem">
            <div class="repairToOtherItem_title">
              <el-cascader
                v-model="repairInfoItem.userId"
                :options="orgPersonList"
                @change="repairUserChange"
                :props="{ expandTrigger: 'hover' }"
              >
                <template slot-scope="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span
                    v-if="node.isLeaf && data.noAbility"
                    style="float: right; color: #999; font-size: 12px"
                    >不推荐</span
                  >
                </template>
              </el-cascader>
              <div class="repairUserHint">
                选择人员会根据维修人员掌握的技能，提示是否推荐其维修当前任务
              </div>
            </div>
            <el-checkbox
              class="repairToOtherItem_checkbox"
              v-model="repairInfoItem.repaired"
              >已修复</el-checkbox
            >
          </div>
        </el-form-item>
        <el-form-item label="其他报警" class="repairTo_formItem">
          <div v-for="item in otherAlarmData" :key="item.id" class="repairToOtherItem">
            <el-checkbox v-model="item.choose"></el-checkbox>
            <div class="repairToOtherItem_title">
              <el-tooltip
                class="item"
                :content="item.warningContent"
                placement="top-start"
              >
                <span class="repairToOtherItem_tipBtn">{{
                  item.warningType + "（" + item.warningLevel + "）"
                }}</span>
              </el-tooltip>
            </div>
            <div class="repairToOtherItem_ability">
              {{ item.ability === "0" ? "不推荐" : "" }}
            </div>
            <el-checkbox
              v-model="item.repaired"
              :disabled="!item.choose"
              class="repairToOtherItem_checkbox"
              >已修复</el-checkbox
            >
          </div>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="closeRepairToDialog()">取消</el-button>
        <el-button type="primary" size="mini" @click="repairAddSave()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MetaChoiceList from "../components/MetaChoiceList";
import MetaPageTable from "../components/MetaPageTable";
import MetaSearchForm from "../components/MetaSearchForm";
import deepClone from "../utils/deepClone";
import utils from "../utils/utils";
export default {
  name: "alarmManagement",
  components: {
    MetaChoiceList,
    MetaPageTable,
    MetaSearchForm,
  },
  data() {
    return {
      roleInfoItem: {},
      alarmLevelDataStr: "",
      choiceListTreeBtn: {
        ifEdit: false,
        ifDelete: false,
      },
      newDepartmentItem: {
        departmentName: "",
        remark: "",
      },
      repairInfoOnChoose: {},
      repairInfoItem: {
        userId: [],
        repaired: false,
      },
      repairToDialogFlag: false,
      alarmRecordDialogFlag: false,
      alarmRecordItem: {},
      alarmRecordData: {},
      editRules: {
        departmentName: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
      },
      repairRules: {
        userId: [{ required: true, message: "请选择人员", trigger: "change" }],
      },
      currentAlarmTableData: [],
      alarmRecordDisplayItem: [
        {
          label: "报警说明",
          prop: "warningContent",
        },
        {
          label: "报警时间",
          prop: "createDate",
        },
      ],
      displayItem: [
        {
          label: "设备名称",
          prop: "equipmentName",
          width: "150",
        },
        {
          label: "设备所在地",
          prop: "address",
          width: "200",
        },
        {
          label: "报警说明",
          prop: "warningContent",
        },
        {
          label: "报警时间",
          prop: "warningTime",
        },
        {
          label: "维修状态",
          prop: "warningStatus",
          type: "if",
          format: {
            0: "",
            1: "已修复",
            2: "修复中",
            3: "已指派",
          },
          color: {
            1: "green",
            2: "orange",
            3: "blue",
          },
        },
        {
          label: "维修人",
          prop: "username",
        },
      ],
      lineBtnGroup: [
        {
          id: "repairTo",
          title: "维修指派",
          hideCheck: this.btnHidecheck,
        },
        {
          id: "alarmRecord",
          title: "报警记录",
        },
      ],
      alertStatusList: [],
      departmentLeftUserList: [],
      searchData: {
        equipmentName: "",
        dateBetween: [],
        province: "",
        city: "",
        areaid: "",
      },
      searchDataForTable: {},
      provinceList: [],
      cityList: [],
      areaList: [],
      collapseActiveNames: [],
      orgPersonList: [],
      otherAlarmData: [],
    };
  },
  created() {},
  mounted() {
    this.initAlarmLevelList();
    this.initPCAList(0, "province");
  },
  destroyed() {},
  methods: {
    getRepairUserData(item, callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "maintenancePerson/getDeptAndPersonList",
        method: "get",
        params: {},
      }).then((res) => {
        if (res.data.code === 200) {
          this.orgPersonList = [];
          for (let i in res.data.result) {
            let orgItem = {};
            orgItem.value = res.data.result[i].deptId;
            orgItem.label = res.data.result[i].deptName;
            orgItem.children = [];
            for (let j in res.data.result[i].list) {
              let personList = {};
              personList.value = res.data.result[i].list[j].userId;
              personList.label =
                res.data.result[i].list[j].name +
                "(" +
                res.data.result[i].list[j].username +
                ")";
              personList.technique = res.data.result[i].list[j].technique;
              let repairContent = res.data.result[i].list[j].technique.split(",");
              let has = false;
              for (let rIndex in repairContent) {
                if (repairContent[rIndex] === item.remarkKey) {
                  has = true;
                  break;
                }
              }
              if (!has) {
                personList.noAbility = true;
              }
              orgItem.children.push(personList);
            }
            this.orgPersonList.push(orgItem);
            if (callback && typeof callback === "function") {
              callback();
            }
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    initAlarmLevelList() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "warning/countEquGroupByWarningLevel",
        method: "post",
        data: {},
      }).then((res) => {
        if (res.data.code === 200) {
          let departmentData = [];
          let currentDataItem = {};
          for (let i in res.data.result) {
            let item = {};
            item = res.data.result[i];
            item.id = res.data.result[i].key;
            item.name =
              res.data.result[i].value +
              " （" +
              res.data.result[i].equipmentNum +
              "台 共" +
              res.data.result[i].warningNum +
              "条）";
            departmentData.push(item);
            if (
              Object.keys(this.roleInfoItem).length > 0 &&
              this.roleInfoItem.id === item.id
            ) {
              currentDataItem = item;
            }
          }
          this.alarmLevelDataStr = JSON.stringify(departmentData);
          if (Object.keys(currentDataItem).length > 0) {
            this.roleInfoItem = deepClone(currentDataItem);
          } else {
            this.roleInfoItem = {};
          }
          this.$nextTick(() => {
            this.$refs.alarmManagement_list.setChoiceRole(this.roleInfoItem);

            if (Object.keys(this.roleInfoItem).length > 0) {
              this.getAlarmEquipmentList(this.roleInfoItem.id);
            }
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    roloeItemChoose(item) {
      if (item.id !== this.roleInfoItem.id) {
        this.roleInfoItem = deepClone(item);
        this.searchData = {
          equipmentName: "",
          dateBetween: [],
          province: "",
          city: "",
          areaid: "",
        };
        this.getAlarmEquipmentList(this.roleInfoItem.id);
      }
    },
    getAlarmEquipmentList(key) {
      let param = this.searchDataForTable;
      param.warningLevel = key;
      param.warningStatus = ["0", "2", "3"];
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "warning/getList",
        method: "post",
        data: param,
      }).then((res) => {
        if (res.data.code === 200) {
          this.currentAlarmTableData = [];
          this.currentAlarmTableData = res.data.result;
          this.collapseActiveNames = [];
          for (let i in res.data.result) {
            this.currentAlarmTableData[i].tableData = {};
            this.currentAlarmTableData[i].tableData.page = 1;
            this.currentAlarmTableData[i].tableData.totalElements =
              res.data.result[i].dataList.length;
            this.currentAlarmTableData[i].tableData.content = res.data.result[i].dataList;

            if (this.currentAlarmTableData[i].tableData.totalElements > 0) {
              this.collapseActiveNames.push(res.data.result[i].typeKey);
            }
          }

          this.$nextTick(() => {
            for (let i in this.currentAlarmTableData) {
              this.$refs[`alarmManagementTable_${i}`][0].formDataInit(true);
            }
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    tableInlineBtnClick(item) {
      if (item.button === "repairTo") {
        this.repairInfoOnChoose = item.rows;
        this.repairInfoItem = {
          userId: [],
          repaired: false,
        };
        this.repairInfoItem.warningId = item.rows.id;
        this.getOtherAlarmSameEqu(item);
        this.getRepairUserData(item, () => {
          this.repairToDialogFlag = true;
        });
      } else if (item.button === "alarmRecord") {
        this.alarmRecordItem = item.rows;
        this.getAlarmRecordData();
      }
    },
    getOtherAlarmSameEqu(alarmItem) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "warning/getNotDealList",
        method: "get",
        params: {
          eId: alarmItem.rows.equipmentId,
          id: alarmItem.rows.id,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.otherAlarmData = [];
          for (let i in res.data.result) {
            let resItem = res.data.result[i];
            resItem.choose = false;
            resItem.repaired = false;
            this.otherAlarmData.push(resItem);
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    getAlarmRecordData() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "warningHistory/getList",
        method: "get",
        params: {
          warningId: this.alarmRecordItem.id,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.alarmRecordData = {};
          this.alarmRecordData.page = 1;
          this.alarmRecordData.totalElements = res.data.result.length;
          this.alarmRecordData.content = res.data.result;

          this.alarmRecordDialogFlag = true;
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    closeAlarmRecordDialog() {
      this.alarmRecordDialogFlag = false;
    },
    repairAddSave() {
      let username = localStorage.getItem("username");
      this.$refs["repair_form"].validate((valid) => {
        if (valid) {
          let data = [];
          let param = {};
          param.warningId = this.repairInfoItem.warningId;
          param.departmentId =
            this.repairInfoItem.userId.length > 0 ? this.repairInfoItem.userId[0] : "";
          param.repairer =
            this.repairInfoItem.userId.length > 1 ? this.repairInfoItem.userId[1] : "";
          param.createUser = username;
          if (!this.repairInfoItem.repaired) {
            param.repairStatus = "3";
          } else {
            param.repairStatus = "1";
          }
          data.push(param);
          for (let i in this.otherAlarmData) {
            if (this.otherAlarmData[i].choose) {
              let item = {};
              item.warningId = this.otherAlarmData[i].id;
              item.departmentId =
                this.repairInfoItem.userId.length > 0
                  ? this.repairInfoItem.userId[0]
                  : "";
              item.repairer =
                this.repairInfoItem.userId.length > 1
                  ? this.repairInfoItem.userId[1]
                  : "";
              item.createUser = username;
              if (!this.otherAlarmData[i].repaired) {
                item.repairStatus = "3";
              } else {
                item.repairStatus = "1";
              }
              data.push(item);
            }
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "repairInfo/save",
            method: "post",
            data: data,
          }).then((res) => {
            if (res.data.code === 200) {
              this.getAlarmEquipmentList(this.roleInfoItem.id);
              this.closeRepairToDialog();
            } else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    closeRepairToDialog() {
      this.repairToDialogFlag = false;
    },
    tableSearch() {
      let param = {};
      for (let key in this.searchData) {
        if (key === "dateBetween") {
          param.startTime =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][0] + " 00:00:00"
              : "";
          param.endTime =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][1] + " 23:59:59"
              : "";
        } else {
          param[key] = this.searchData[key];
        }
      }
      this.searchDataForTable = param;
      this.getAlarmEquipmentList(this.roleInfoItem.key);
    },
    provinceHandleChange(id) {
      this.cityList = [];
      this.areaList = [];
      this.searchData.city = "";
      this.searchData.areaid = "";
      if (id !== "") {
        this.initPCAList(id, "city");
      }
    },
    cityHandleChange(id) {
      this.areaList = [];
      this.searchData.areaid = "";
      if (id !== "") {
        this.initPCAList(id, "area");
      }
    },
    initPCAList(id, type, callback) {
      if (id === "") {
        return;
      }
      let data = {};
      if (type === "province") {
        data.level = 1;
      } else if (type === "city") {
        data.level = 2;
      } else if (type === "area") {
        data.level = 3;
      }
      data.parentid = id;
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/company/area",
        method: "post",
        data: data,
      }).then((res) => {
        if (type === "province") {
          this.provinceList = res.data.result;
        } else if (type === "city") {
          this.cityList = res.data.result;
        } else if (type === "area") {
          this.areaList = res.data.result;
        }
        if (callback && typeof callback === "function") {
          callback();
        }
      });
    },
    btnHidecheck(rowData, item) {
      if (rowData.warningStatus === "0" && item.id === "repairTo") {
        return true;
      }
      return false;
    },
    repairUserChange() {
      if (this.repairInfoItem.userId.length == 2) {
        let technique = "";
        for (let i in this.orgPersonList) {
          if (this.repairInfoItem.userId[0] === this.orgPersonList[i].value) {
            for (let j in this.orgPersonList[i].children) {
              if (
                this.repairInfoItem.userId[1] === this.orgPersonList[i].children[j].value
              ) {
                technique = this.orgPersonList[i].children[j].technique;
                break;
              }
            }
          }
        }
        for (let i in this.otherAlarmData) {
          let repairContent = technique.split(",");
          let has = false;
          for (let rIndex in repairContent) {
            if (repairContent[rIndex] === this.otherAlarmData[i].warning_type) {
              has = true;
              this.otherAlarmData[i].ability = "1";
              break;
            }
          }
          if (!has) {
            this.otherAlarmData[i].ability = "0";
          }
        }
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.alarmManagement {
  width: 100%;
  height: 100%;
  display: flex;
  flex-grow: 1;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .alarmManagement_treeBg {
    height: 100%;
  }
  .alarmManagement_infoBg {
    height: 100%;
    box-sizing: border-box;
    padding: 0 7px;
    flex: 1;
  }
  .alarmManagement_info {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    border: 1px solid rgb(228, 234, 236);
    flex: 1;
    overflow-y: scroll;
    box-sizing: border-box;
    padding: 15px;
    .alarmManagementO_rightArea {
      .alarmManagementTable_bg {
        width: 100%;
        float: left;
        .alarmManagementTable {
          float: left;
          width: 100%;
          overflow-y: unset;
        }
      }
      .alarmManagement_searchFromItem {
        float: left;
      }
    }
  }
  .alarmRecordForm_item {
    .el-form-item__label {
      color: #333 !important;
    }
  }
  .alarmRecordTable {
    width: 100%;
    overflow-y: unset;
  }
  .repairTo_formItem {
    margin-bottom: 10px;
    .repairToOtherItem {
      display: flex;
      .repairToOtherItem_title {
        flex: 2;
        .repairToOtherItem_tipBtn {
          cursor: pointer;
        }
        .repairUserHint {
          font-size: 12px;
          color: rgb(179, 114, 30);
          height: 25px;
          line-height: 25px;
        }
      }
      .repairToOtherItem_ability {
        width: 50px;
        font-size: 14px;
        color: #999;
      }
      .repairToOtherItem_checkbox {
        flex: 1;
        text-align: center;
      }
    }
  }
  .repairTo_user {
    padding-bottom: 26px;
    border-bottom: 1px solid #f1f1f1;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
